﻿using CardService;
using HsPrint.Ut;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ParkService;
using ParkService.Ut;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace EWGprint
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        #region WebSoket通讯服务
        WSocketServer _server = null;
        bool _isRunning = false;
        /// <summary>
        /// 座席端掉线
        /// </summary>
        /// <param name="obj"></param>
        private void _server_Closed(SuperWebSocket.WebSocketSession obj)
        {
            //  System.Diagnostics.Debug.WriteLine($"Closed {System.Web.HttpUtility.UrlDecode(obj.Path, System.Text.Encoding.UTF8)}");
        }
        /// <summary>
        /// 有新用户建立连接
        /// </summary>
        /// <param name="obj"></param>
        private void Server_NewConnected(SuperWebSocket.WebSocketSession obj)
        {
            //对新链接做处理，验证链接是否合法等等，不合法则关闭该链接
            //新链接进行数据初始化

            //  System.Diagnostics.Debug.WriteLine($"NewConnected {System.Web.HttpUtility.UrlDecode(obj.Path, System.Text.Encoding.UTF8)}");
        }
        /// <summary>
        /// 收到用户消息
        /// </summary>
        /// <param name="arg1"></param>
        /// <param name="arg2"></param>
        private void Server_MessageReceived(SuperWebSocket.WebSocketSession arg1, string arg2)
        {
            //接收到客户端链接发送的东西
            new Logger().Debug($"from {System.Web.HttpUtility.UrlDecode(arg1.Path, System.Text.Encoding.UTF8)} => {arg2}");
            //处理对应业务
            AnalyzeData(arg2);
        }

        public bool Start(int svrPort)
        {
            _isRunning = true;
            var result = _server.Open(svrPort, "ParkSocket", false, "Park", "tls", "", "", "");
            return result;
        }
        public void Stop()
        {
            _isRunning = false;
            _server.Dispose();
        }
        /// <summary>
        /// 启动服务
        /// </summary>
        public void InitSvr()
        {
            try
            {
                _server = new WSocketServer();
                _server.MessageReceived += Server_MessageReceived;
                _server.NewConnected += Server_NewConnected;
                _server.Closed += _server_Closed;
            }
            catch (Exception ex)
            {
                new Logger().Error(ex.ToString());
            }
            if (Start(AppInfo.PrtPort))
            {
                new Logger().Debug("服务安装成功,且已启动...");
                this.labMsg.Text = "服务安装成功,且已启动";
            }
            else
            {
                new Logger().Debug("服务启动失败...");
                MessageBox.Show("服务启动失败", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.labMsg.Text = "服务启动失败";
                this.labMsg.ForeColor = Color.Red;
            }
        }
        #endregion

        #region 解析收到的消息
        /// <summary>
        /// 解析收到的消息
        /// </summary>
        /// <param name="DataInfo"></param>
        private void AnalyzeData(string _DataInfo)
        {
            try
            {
                new Logger().Debug("解析收到的消息:" + _DataInfo);
                if (_DataInfo.Contains("prttype"))
                {
                    PrintMethod(_DataInfo);
                }
            }
            catch (Exception Ex)
            {
                new Logger().Error("分析接收到的消息时出错： " + Ex.Message);
            }
        }
        void PrintMethod(string _DataInfo)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate { ShowPrint(_DataInfo); }));
            }
            else
            {
                ShowPrint(_DataInfo);
            }
        }
        void ShowPrint(string _DataInfo)
        {
            try
            {
                if (!string.IsNullOrEmpty(_DataInfo))
                {
                    JObject obj = (JObject)JsonConvert.DeserializeObject(_DataInfo);
                    string _prttype = obj["prttype"].ToString();
                    if (_prttype == "reacardnum")
                    {
                        ReacardNum(); //读卡
                    }
                    else if (_prttype == "readnfccard")
                    {
                        ReacardNfcNum(); //读卡
                    }
                }
            }
            catch (Exception ex)
            {
                new Logger().Error(ex.Message);
            }
        }
        #endregion

        #region 读卡应用
        /// <summary>
        /// 读卡应用
        /// </summary>
        void ReacardNum()
        {
            try
            {
                var result = new D8API().ReadCardId();
                if (result != null)
                {
                    var rpmsg = Newtonsoft.Json.JsonConvert.SerializeObject(result);
                    foreach (var item in _server.WebSocket.GetAllSessions())
                    {
                        //执行推送
                        new Logger().Debug(item.Path.Replace("/", "") + ";执行推送");
                        _server.SendMessage(item, rpmsg);
                    }
                }
            }
            catch(Exception ex)
            {
                new Logger().Error(ex.Message);
            }
        }
        /// <summary>
        /// 读卡应用_Nfc
        /// </summary>
        void ReacardNfcNum()
        {
            try
            {
                var result = new D8API().ReadIcNo();
                if (result != null)
                {
                    var rpmsg = Newtonsoft.Json.JsonConvert.SerializeObject(result);
                    foreach (var item in _server.WebSocket.GetAllSessions())
                    {
                        //执行推送
                        new Logger().Debug(item.Path.Replace("/", "") + ";执行推送");
                        _server.SendMessage(item, rpmsg);
                    }
                }
            }
            catch (Exception ex)
            {
                new Logger().Error(ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.HideServer();
        }

        #region notifyIcon
        private bool showFlag = false;
        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.showFlag = true;
            this.menuItem_Hide.Enabled = true;
            this.menuItem_Show.Enabled = false;
        }

        private void menuItem_Show_Click(object sender, EventArgs e)
        {
            this.ShowServer();
        }

        private void menuItem_Hide_Click(object sender, EventArgs e)
        {
            this.HideServer();
        }
        /// <summary>
        /// 隐藏窗体
        /// </summary>
        private void HideServer()
        {
            this.Hide();
            this.showFlag = false;
            this.menuItem_Hide.Enabled = false;
            this.menuItem_Show.Enabled = true;
        }

        /// <summary>
        /// 显示窗体
        /// </summary>
        private void ShowServer()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            this.showFlag = true;
            this.menuItem_Hide.Enabled = true;
            this.menuItem_Show.Enabled = false;
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItemExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要退出服务吗(关闭后,将应用一卡通使用)？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                this.notifyIcon1.Dispose();
                System.Diagnostics.Process.GetCurrentProcess().Kill();//强制杀进程结束程序
                Application.Exit();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        private void FrmMain_Load(object sender, EventArgs e)
        {
            try
            {
                //设置开机自启动  
                WriteRegistry();
                this.Close();
            }
            catch(Exception ex)
            {
                new Logger().Error(ex.Message);
            }
        }

        #region 开机启动
        /// <summary>
        /// 开机启动
        /// </summary>
        private void WriteRegistry()
        {
            string strName = Application.ExecutablePath;
            if (File.Exists(strName))
            {
                string strNewName = Path.GetFileName(strName);
                RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (reg == null)
                {
                    reg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                else
                {
                    if (reg.GetValue(strNewName) == null)
                    {
                        reg.SetValue(strNewName, strName);
                    }
                }
            }
        }
        #endregion

        #region 测试读卡
        /// <summary>
        /// 测试读卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            var result = new D8API().ReadCardId();
            try
            {
                if (result != null)
                {
                    if (result.ret == 1)
                    {
                        string CatCardNo = result.catcardno;
                        string CardNo =result.cardno;
                        var _data = result.catcardno + "|" + result.cardno+"|"+ result.personInfo.certNo + "|"+ result.personInfo.fullName;
                        MessageBox.Show(_data);
                    }
                    else
                    {
                        MessageBox.Show(result.msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }            
            }
            catch(Exception ex)
            {
                MessageBox.Show("读卡结果:"+ result+";异常："+ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 测试读取手机NFC
        /// <summary>
        /// 测试读取手机NFC
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            var result = new D8API().ReadIcNo();
            try
            {
                if (result != null)
                {
                    if (result.ret == 1)
                    {
                        string CardNo = result.cardno;
                        var _data = result.catcardno;
                        MessageBox.Show("卡号是:"+_data);
                    }
                    else
                    {
                        MessageBox.Show(result.msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("读卡结果:" + result + ";异常：" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion
    }
}
